<template>
  <el-card>
    <!-- 数据表格 -->
    <div class="table-container">
      <div class="mb-2.5">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button type="primary" :icon="CirclePlus" @click="openDialogForm(true)">新增</el-button>
          </el-col>
          <el-col :span="12">
            <div class="flex justify-end">
              <el-button :icon="RefreshRight" circle @click="handleSearchFormReset"></el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%;"
                  row-key="id"
                  default-expand-all
        >
          <el-table-column align="left" prop="cate_name" label="分类名称"></el-table-column>
          <el-table-column align="center" prop="image" label="图标">
            <template #default="scope">
              <el-image
                v-if="scope.row.image"
                fit="cover"
                style="width: 28px; height: 28px;"
                :src="scope.row.image"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="mark" label="标识"></el-table-column>
          <el-table-column align="center" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusInfo(scope.row.status).type">
                {{ getStatusInfo(scope.row.status).text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="openDialogForm(false, scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog v-model="formShow" :title="dialogTitle" width="700">
      <el-form ref="formDataRef" class="pa-5" :rules="rules" :model="formData" label-position="right"
               label-width="auto">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类名称" prop="cate_name">
              <el-input v-model="formData.cate_name" placeholder="请输入分类名称" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="唯一标识" prop="mark">
              <el-input v-model="formData.mark" placeholder="请输入分类标识" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="父级分类">
              <el-tree-select
                  v-model="formData.pid"
                  :props="defaultProps"
                  :data="tableData"
                  :render-after-expand="false"
                  check-strictly
                  value-key="id"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类图片" prop="status">
              <Upload :multiple="false" v-model="formData.image" text="上传图片" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, computed, nextTick} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import {RefreshRight, Search, CirclePlus} from '@element-plus/icons-vue'
import Upload from '@/components/Upload.vue'
import {
  getArticleCateListApi,
  getArticleCateInfoApi,
  saveArticleCateInfoApi,
  updateArticleCateInfoApi,
  deleteArticleCateInfoApi
} from '@/api/articleCate'

// 配置项
const defaultProps = {
  value: 'id', // 选中值的字段
  label: 'cate_name', // 显示文本的字段
  children: 'children', // 子节点的字段
};

// 表格数据
const tableData = ref([]);
// 是否显示搜索表单视图
const SearchShow = ref(true);
// 表单对话框
const formShow = ref(false);
// 对话框标题
const dialogTitle = computed(() => (isAdd.value ? '新增分类' : '编辑分类'));
// 搜索字段
const searchForm = ref({});
// 提交表单ref
const formDataRef = ref<FormInstance>();
// 是否新增
const isAdd = ref(false);

// 接口类型
interface FormDataTypes {
  id?: number
  cate_name: string
  pid: number
  mark: string
  status: number
  image: string
}

// 表单数据字段
const initForm = reactive<FormDataTypes>({
  cate_name: '',
  mark: '',
  pid: 0,
  status: 1,
  image: ''
});

// 表单数据字段
const formData = reactive<FormDataTypes>({...initForm});

// 独立的重置表单方法
const resetForm = async () => {
  // 深拷贝初始值
  const deepCloneInit = JSON.parse(JSON.stringify(initForm));
  Object.assign(formData, deepCloneInit);
  
  await nextTick();
  if (formDataRef.value) {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  }
};

const rules = ref<FormRules<FormDataTypes>>({
  cate_name: [
    {required: true, message: '分类名称必填', trigger: 'change'},
    {max: 15, message: '分类名称长度为不能超过15个字符', trigger: 'change'},
  ]
});

// 状态标签
const statusMap = {
  1: {type: 'primary', text: '启用'},
  0: {type: 'danger', text: '禁用'}
} as const;

const getStatusInfo = (status: number) => statusMap[status] || {type: 'info', text: '未知状态'};

// 加载表格数据
const loadTableData = async () => {
  const response = await getArticleCateListApi({
    ...searchForm.value, // 拼接搜索条件
  });
  tableData.value = response.data
};

// 重置搜索表单
const handleSearchFormReset = () => {
  searchForm.value = {};
  loadTableData(); // 重新加载初始数据
};

// 删除行数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除此数据吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // 执行删除操作
    await deleteArticleCateInfoApi(row.id);
    // 刷新表格数据
    await loadTableData();
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 打开对话表单
const openDialogForm = async (isNew: boolean, row?: { id: number }) => {
  resetForm(); // 先完成重置
  formShow.value = true; // 显示对话框
  isAdd.value = isNew;
  
  // Object.assign(formData, initForm);
  await nextTick(() => {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  });

  if (!isAdd.value) {
    // 编辑时获取分类信息
    const response = await getArticleCateInfoApi(row.id);
    Object.assign(formData, response.data); // 将接口数据合并到 formData 中
  }
};

// 关闭对话表单
const handleClose = () => {
  formShow.value = false;
}

// 提交分类表单
const handleSubmit = async () => {
  if (!formDataRef.value) return;

  // 校验表单
  await formDataRef.value.validate();

  // 判断是否为新增或更新
  const isUpdate = !!formData.id; // 如果存在 id，则为更新操作

  // 执行新增或更新操作
  if (isUpdate) {
    // 更新操作
    await updateArticleCateInfoApi(formData.id, formData);
    ElMessage.success('更新成功');
  } else {
    // 新增操作
    await saveArticleCateInfoApi(formData);
    ElMessage.success('新增成功');
  }

  // 关闭对话框并刷新表格数据
  handleClose();
  await loadTableData();
};

onMounted(() => {
  loadTableData(); // 在组件挂载后加载数据
});
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-wrapper {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}
</style>